package hot100;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class Solution94 {
    List<Integer> list = new LinkedList<>();
    Deque<TreeNode> stack = new LinkedList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        while (root != null || !stack.isEmpty()) {
            // 一直遍历左子树
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            // 取出最左节点
            root = stack.pop();
            list.add(root.val);
            // 处理当前节点的右节点
            root = root.right;
        }
        return list;
    }

    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left);
        list.add(root.val);
        dfs(root.right);
    }

    private void morris(TreeNode root) {
        while (root != null) {
            if (root.left == null) {
                list.add(root.val);
                root = root.right;
            } else {
                TreeNode predecessor = getPredecessor(root);
                if (predecessor.right == null) {
                    predecessor.right = root;
                    root = root.left;
                } else {
                    list.add(root.val);
                    root = root.right;
                }
            }
        }
    }

    private TreeNode getPredecessor(TreeNode node) {
        TreeNode right = null;
        while (node != null) {
            right = node;
            node = node.right;
        }
        return right == null ? node.left : right;
    }

}
